<?php
namespace Controller;

class PostControllerOutput {
	public $m_postHtml = "";
}

class PostController {

	/**
	 * @return PostControllerOutput
	 */
	private static $edit = "edit";

	public function doControll(\Model\PostHandler $posthandler, \Model\Database $database) {

		$post = \View\NavigationView::getSelectedPost($posthandler, $database);
		$loginhandler = new \Model\LoginHandler($database);
		$postView = new \View\PostView();
		$commentController = new \Controller\CommentController();
		$out = new PostControllerOutput();
		$p_id = $post -> getId();
		$title = $post -> getTitle();
		$content = $post -> getContent();
		$message = "";

		//Om användaren är inloggad funkar allt detta
		if ($loginhandler -> IsLoggedIn() == true) {
			//Delete
			if ($postView -> TriedToDelete() == true) {

				$messageid = $posthandler -> DeletePost($p_id);

				if ($messageid == true) {
					$message .= $postView -> newPostMess(\View\PostView::POST_DELETED);
					header('Location:index.php ');
				} else {
					$message .= $postView -> newPostMess(\View\PostView::POST_NOT_DELETED);
				}
			}
			//Om användaren trycker på redigera
			if ($postView -> TriedToEdit() == true) {

				header('Location: index.php?postID=' . $p_id . "&edit");
			}

			if (isset($_GET[self::$edit])) {

				$out -> m_postHtml = $postView -> EditPostForm($post);

				if ($postView -> TriedToEditSubmit() == true) {

					$messageid = $posthandler -> EditPost($p_id, $postView -> Title(), $postView -> Content());

					if ($messageid == \Model\PostHandler::POST_EMPTY) {
						$message .= $postView -> NewPostMess(\View\PostView::POST_EMPTY);
					}
					if ($messageid == \Model\PostHandler::POST_SAVED) {
						$message .= $postView -> NewPostMess(\View\PostView::POST_SAVED);
						//header('Refresh: 1; URL=index.php?postID=' . $p_id);
						header('Location: index.php?postID=' . $p_id);
					}
					if ($messageid == \Model\PostHandler::POST_FAILED) {
						$message .= $postView -> NewPostMess(\View\PostView::POST_FAILED);
					}
					$out -> m_postHtml .= $message;

					if ($message != $postView -> NewPostMess(\View\PostView::POST_SAVED)) {
						$out -> m_postHtml = $message;
						$out -> m_postHtml .= $postView -> EditPostForm($post);

					}

					if ($message == $postView -> NewPostMess(\View\PostView::POST_SAVED)) {
						$out -> m_postHtml .= $message;

						$out -> m_postHtml .= $postView -> showPost($post, $database);

						header('Location: index.php?postID=' . $p_id);

					}
				}
				return $out;

			}
		}
		$out -> m_postHtml .= $postView -> showPost($post, $database);
		$out -> m_postHtml .= $commentController -> DoControll($database, $p_id);
		return $out;
	}

}
